<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/1/15
 * Time: 23:05
 */
namespace app\admin\logic\statistics;



use app\common\model\zbtask\Money;
use app\common\utils\Utils;
use think\Db;

class MoneyStatistics
{
    private static $new; //申请一个私有的静态成员变量来保存该类的唯一实例
    private $where = [];
    public $model;
    private $field = ['sum(money.money) as moneySum', 'sum(money.get_money) as get_money', 'sum(money.already_money) as already_money','count(money.id) as nums'];
    private function __construct() {
        $this->request = request();
        $this->model = new Money();
    }


    public static function instance () { //声明一个静态公共方法，供外部获取唯一实例
        if (!(self::$new instanceof self)) {
            self::$new = new self;
        }
        return self::$new;
    }

    /** 设置where*/
    public function setWhere($where = []) {
        $this->where = $where;
        return $this;
    }
    public function setField($field = []) {
        $this->field = $field;
        return $this;
    }

    public function getRes() {
        $res = $this->model->with(['user','zbtask'])->where($this->where)->field($this->field)->find();
        $res = $res->toArray();
        foreach ($res as $k => $v) {
            if (!$v) {
                $res[$k] = 0;
            }
        }

        return $res;
    }

    public static  function toDefaultString($res) {
        $str = "总应发：{$res['moneySum']},总实发：{$res['get_money']}, 总纳税金额：{$res['already_money']}, 总数量：{$res['nums']}";

        return $str;
    }

    /**
     * 计算经销商佣金
     * @return float|int
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getDealerMoney(){
        $money_data = $this->model->alias('money')
            ->join('zbtask zbtask', 'money.task_id = zbtask.id')
            ->join('dealer_company dealer_com', 'zbtask.company_id = dealer_com.company_id')
            ->field(['money.money', 'dealer_com.rate'])
            ->where($this->where)
            ->select();
        $dealer_money_amount = 0;
        $money_list = collection($money_data)->toArray();
        foreach($money_list as $value){
            $dealer_money_amount += round(Utils::processMoney($value['money'], $value['rate'], '*', 5), 2);
        }
        return $dealer_money_amount;
    }

}